/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.csvgenerator;

import com.csvgenerator.engine.value.ValueProducer;
import com.csvgenerator.engine.value.ValueProducerLookup;
import com.csvgenerator.settings.GlobalSettings;
import com.csvgenerator.inputmodel.parser.InputModelSAXHandler;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;

/**
 *
 * @author Administrator
 */
public class CSVGenerator {

    private DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    private Long numberOfRows;
    private Long numberOfRowsPerFile;
    private String inputFile;
    private String outputFile;
    private List<ValueProducer> valueProducers;
    private boolean initialized = false;

    public CSVGenerator(Long numberOfRows, Long numberOfRowsPerFile, String inputFile, String outputFile) {
        this.numberOfRows = numberOfRows;
        this.numberOfRowsPerFile = numberOfRowsPerFile;
        this.inputFile = inputFile;
        this.outputFile = outputFile;
    }

    /**
     * Initialize CSVGenerator with input model file
     */
    private void init() {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();            
            SAXParser saxParser = factory.newSAXParser();                    
            saxParser.parse(inputFile, new InputModelSAXHandler());
            
            valueProducers = ValueProducerLookup.getInstance().getValueProducersList(); 

        } catch (IOException ex) {
            Logger.getLogger(CSVGenerator.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(CSVGenerator.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(CSVGenerator.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Generate CSV output file
     */
    public void generate() {
        if (!initialized) {
            init();
        }
        
        long startTime = System.currentTimeMillis();
        System.out.println("Generation process started at : " + dateFormat.format(new Date()));

        StringBuilder lineSB = new StringBuilder();
        File f = null;
        FileWriter fw = null;
        int j = 0;
        int i = 0;

        while (j < numberOfRows) {
            try {
                f = new File(
                        outputFile.substring(0, outputFile.indexOf("."))
                        + "_" + i
                        + outputFile.substring(outputFile.indexOf(".")));

                if (f.exists()) {
                    f.delete();
                }
                System.out.println("Populating file " + f + "...");
                fw = new FileWriter(f, true);

                for (long l = 0; l < numberOfRowsPerFile; l++, j++) {
                    lineSB.delete(0, lineSB.length());
                    for (ValueProducer vp : valueProducers) {                        
                        //skip negative VPs, because they are driven manually
                        if (vp.getId()<0) continue;
                        
                        if (!vp.isHidden()) {
                            lineSB.append(vp.nextValue()).append(GlobalSettings.delimiter);
                        } else {
                            vp.nextValue();
                        }
                    }
                    fw.write(lineSB.toString() + GlobalSettings.row_delimiter);
                }
                i++;

            } catch (IOException ex) {
                System.out.println("ex" + ex);
            } finally {
                try {
                    fw.close();
                    System.out.println("Populating file " + f + " finished.");
                } catch (IOException ex) {
                    System.out.println(ex);
                }
            }
        }
        long duration = System.currentTimeMillis() - startTime;
        System.out.println("Generation process finished at : " + dateFormat.format(new Date()));
        System.out.println("Duration " + duration / 1000 + "s [" + duration + "ms]\n");
    }

    
}
